import MyComponent from "../classes/MyComponent.js";
import {generateElement} from "../functions/common.js";

export class MyTable extends MyComponent {
    constructor(){
        super();
        this.elem = generateElement({
            type: "table",
            className: "layui-table",
            width: "400px",
            overflow: "hidden",
        });
        this.elem.innerHTML = "<thead><tr></tr></thead>\n" +
            "            <tbody></tbody>";
        this.myTable = this.elem;
    }
    init(){
        this.myTBody = this.myTable.querySelector("tbody");
        this.myTHead = this.myTable.querySelector("thead");
        this.myTHeadTr = this.myTHead.querySelector("tr");
    }
    insertValue(tdStrList){
        let trElem = generateElement({
            type: "tr",
        });
        trElem.appendChild(generateElement({
            type: "td",
            innerText: "0",
        }));
        for (let i = 0; i < tdStrList.length; i++) {
            trElem.appendChild(generateElement({
                type: "td",
                innerText: tdStrList[i],
            }))
        }
        this.myTBody.appendChild(trElem);
    };
    addTHeadTh(newHead){
        this.myTHeadTr.appendChild(generateElement({
            type: "th",
            innerText: newHead,
        }));
    };
    resetTableIndex(){
        let tBodyTrList = this.myTBody.querySelectorAll("tr");
        for (let i = 0;i<tBodyTrList.length;i++){
            tBodyTrList.item(i).querySelector("td").innerHTML = i.toString();
        }
    };
    deleteTr(index) {
        try {
            anime({
                targets: this.myTBody.childNodes[index],
                translateX: -1000,
                complete: (a) => {
                    this.myTBody.removeChild(this.myTBody.childNodes[index]);
                    this.resetTableIndex();
                },
                easing: 'easeOutQuad',
            });
        } catch (e) {
            console.error("Error", e)
        }
    };
    insertTr(tdStrList, callBack){
        this.insertValue(tdStrList);
        let location = this.myTBody.childNodes.length;
        try {
            anime({
                targets: this.myTBody.childNodes[location - 1],
                translateX: 1000,
                direction: 'reverse',
                easing: 'easeOutQuad',
                complete: (a) => {
                    // this.resetTableIndex();
                    if (callBack){
                        callBack();
                    }
                }
            });
        } catch (e) {
            console.error("Error", e)
        }
    };
}
